<template>
  <el-container class="common-layout">
    <el-header class="header">
      <span>角色管理</span>
    </el-header>

    <el-main class="content-area">
      <el-table :data="roles" style="width: 100%" border stripe>
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="viewRoleUsers(row.id)">
              查看用户
            </el-button>
            <el-button type="text" size="small" @click="editRoleUsers(row)">
              编辑用户角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <!-- 查看角色用户对话框 -->
    <el-dialog
      v-model="roleUsersDialogVisible"
      :title="`角色「${currentRoleName}」的用户`"
      width="50%"
    >
      <el-table :data="roleUsers" style="width: 100%" border stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" size="small" style="color:#f56c6c" @click="deleteUserRoles(row.id)">
              删除绑定
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="roleUsersDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户角色对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户角色"
      width="50%"
      @close="resetEditForm"
    >
      <el-form ref="editFormRef" :model="editForm" label-width="100px">
        <el-form-item label="用户">
          <el-select v-model="editForm.userId" placeholder="选择用户" style="width: 100%">
            <el-option v-for="user in allUsers" :key="user.id" :label="user.username" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.roleIds" multiple placeholder="选择角色" style="width: 100%">
            <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditRoles" :loading="editLoading">保存</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义类型
interface Role {
  id: number
  name: string
  description: string
}

interface User {
  id: number
  username: string
  email?: string
  mobile?: string
  isActive?: boolean
}

interface RoleUser {
  id: number
  username: string
  roles?: number[]
}

interface EditForm {
  userId: number | null
  roleIds: number[]
}

// 角色数据
const roles = ref<Role[]>([
  { id: 1, name: '管理员', description: '系统最高权限' },
  { id: 2, name: 'VIP会员', description: '可修改自己信息' },
  { id: 3, name: '普通用户', description: '只能查看部分数据' }
])

// 用户数据 - 修复类型问题
const allUsers = ref<User[]>([])

// 查看角色用户
const roleUsersDialogVisible = ref(false)
const roleUsers = ref<RoleUser[]>([])
const currentRoleName = ref('')

const viewRoleUsers = async (roleId: number) => {
  currentRoleName.value = roles.value.find(r => r.id === roleId)?.name || ''
  try {
    const res = await axios.get(`/api/role_users/${roleId}`)
    roleUsers.value = res.data || []
    roleUsersDialogVisible.value = true
  } catch {
    ElMessage.error('加载角色用户失败')
  }
}

// 删除单个用户角色绑定
const deleteUserRoles = async (userId: number) => {
  try {
    await ElMessageBox.confirm('确认删除该用户所有角色绑定？', '警告', { type: 'warning' })
    await axios.delete(`/api/user_roles/${userId}`)
    ElMessage.success('删除成功')
    // 刷新当前列表
    roleUsers.value = roleUsers.value.filter(u => u.id !== userId)
  } catch (err) {
    if ((err as any) !== 'cancel') ElMessage.error('删除失败')
  }
}

// 编辑用户角色
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive<EditForm>({ 
  userId: null, 
  roleIds: [] 
})
const editLoading = ref(false)

const editRoleUsers = async (role: Role) => {
  try {
    const res = await axios.get(`/api/role_users/${role.id}`)
    const users = res.data || []
    
    if (users.length > 0) {
      editForm.userId = users[0].id
      editForm.roleIds = users[0].roles || []
    } else {
      editForm.userId = null
      editForm.roleIds = []
    }
    
    editDialogVisible.value = true
  } catch {
    ElMessage.error('加载用户角色失败')
  }
}

const submitEditRoles = async () => {
  if (!editForm.userId) {
    ElMessage.warning('请选择用户')
    return
  }
  
  editLoading.value = true
  try {
    await axios.put(`/api/user_roles/${editForm.userId}`, { roleIds: editForm.roleIds })
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    
    // 如果角色列表对话框打开，刷新
    if (roleUsersDialogVisible.value && editForm.roleIds.length > 0) {
      const role = roles.value.find(r => r.id === editForm.roleIds[0])
      if (role) {
        await viewRoleUsers(role.id)
      }
    }
  } catch {
    ElMessage.error('更新失败')
  } finally {
    editLoading.value = false
  }
}

const resetEditForm = () => {
  editForm.userId = null
  editForm.roleIds = []
}

// 初始化用户列表
const loadUsers = async () => {
  try {
    const res = await axios.get('/api/users')
    // 确保数据格式正确
    allUsers.value = Array.isArray(res.data?.data) ? res.data.data : []
  } catch {
    ElMessage.error('加载用户失败')
    allUsers.value = []
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.common-layout { 
  height: 100vh; 
  display: flex; 
  flex-direction: column; 
}
.header { 
  background-color: #409eff; 
  color: white; 
  display: flex; 
  align-items: center; 
  padding: 0 20px; 
}
.content-area { 
  padding: 20px; 
  background-color: #f5f7fa; 
}
</style>